package com.org.manhu.chargehelper.ui;

import java.util.Map;

import com.org.manhu.chargehelper.ChargeApplication;
import com.org.manhu.chargehelper.R;
import com.org.manhu.chargehelper.broadcastreceiver.UpdateMoneyReceiver;
import com.org.manhu.chargehelper.broadcastreceiver.UpdateNickNameReceiver;
import com.org.manhu.chargehelper.constant.Constant;
import com.org.manhu.chargehelper.custom.BatteryCharger;
import com.org.manhu.chargehelper.tools.AppManager;
import com.org.manhu.chargehelper.tools.DeviceInfo;
import com.org.manhu.chargehelper.tools.JsonUtil;
import com.org.manhu.chargehelper.tools.NetUtils;
import com.org.manhu.chargehelper.tools.SharedPreferncesUtil;
import com.org.manhu.chargehelper.tools.ToastUtils;
import com.org.manhu.chargehelper.webservice.AsyncProcessData;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * @文件名：CashOutActivity.java
 * @包名：com.org.manhu.chargehelper.ui
 * @作者：李朋辉 @QQ：892839211
 * @创建时间：2015年2月5日 下午4:29:10
 *
 * @描述：
 */
public class CashOutActivity extends Activity implements OnClickListener {

	private ImageView backIv, userInfoMoreIv;
	private Button exchangeBtn, cashOutBtn;

	private EditText weixinAccountEdt, moneyEdt;
	private Button addBtn, reduceBtn, sureBtn, cancleBtn;
	private RelativeLayout userInfo;
	private BatteryCharger battery;

	private String weixinAccount;
	private int money;
	private float awardNum;
	private AsyncProcessData request;
	private TextView awardNumTv, userNameTv;
	private UpdateNickNameReceiver mReceiver;
	private UpdateMoneyReceiver receivers;

	private String channelId;
	private String devId;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			String json = msg.getData().getString("jsonStr");
			if (Constant.CLIENT_INIT.equals(msg.obj.toString())) {
				Map<String, String> map = JsonUtil.parseToMap(json);
				if (map != null) {
					ChargeApplication.updateInitInfo(map);
					userCashOut(ChargeApplication.getInitInfo().get("AuthKey"));
				} else {
					clientInit();
				}
			} else if (Constant.USER_CASH_OUT.equals(msg.obj.toString())) {
				Map<String, String> feedbackMap = JsonUtil.parseAll(json);
				if (feedbackMap != null) {
					if (feedbackMap.get("Code").equals("0")) {
						clientInit();
					} else {
						Map<String, String> cashOutMap = JsonUtil
								.parseAll(json);
						if (cashOutMap != null) {
							if ("1".equals(cashOutMap.get("Code"))) {
								CashOutActivity.this.finish();
								awardNumTv.setText(awardNum - money + "");
								SharedPreferncesUtil.saveMoney(
										CashOutActivity.this, awardNum - money);
							}
							ToastUtils.showShort(CashOutActivity.this,
									cashOutMap.get("Description"));
						}
					}
				} else {
					userCashOut(ChargeApplication.getInitInfo().get("AuthKey"));
				}
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cash_out);
		AppManager.getAppManager().addActivity(this);
		init();

		request = new AsyncProcessData();

		mReceiver = new UpdateNickNameReceiver(userNameTv);
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.ACTION_UPDATE_NICKNAME);
		registerReceiver(mReceiver, filter);

		receivers = new UpdateMoneyReceiver(awardNumTv);
		IntentFilter filters = new IntentFilter();
		filter.addAction(Constant.ACTION_UPDATE_MONEY);
		registerReceiver(receivers, filters);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		awardNumTv.setText(SharedPreferncesUtil.getMoney(this) + "");
		userNameTv.setText(SharedPreferncesUtil.getNickName(this));
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mReceiver);
		unregisterReceiver(receivers);
	}

	/**
	 * @描述： 客户端初始化，获取AuthKey
	 */
	private void clientInit() {
		if (NetUtils.isConnected(this)) {
			if (Constant.IS_USE_BOXINFO) {
				channelId = SharedPreferncesUtil.getBoxInfo(this,
						Constant.SP_BOX_CHANNELID);
				devId = SharedPreferncesUtil.getBoxInfo(this,
						Constant.SP_BOX_DEVID);
			} else {
				channelId = "0";
				devId = "0";
			}
			request.getRequestData(mHandler, Constant.CLIENT_INIT, "AuthKey",
					"", "Imei", DeviceInfo.getIMEI(), "Imsi",
					DeviceInfo.getIMSI(), "AndroidId",
					DeviceInfo.getAndroidID(), "PhoneTypeId",
					DeviceInfo.getDeviceModel(), "ChannelId", channelId,
					"DevId", devId);
		} else {
			ToastUtils.showShort(this, "网络异常，请稍检查网络");
		}
	}

	/**
	 * @描述： 初始化，并设置监听
	 */
	private void init() {
		backIv = (ImageView) findViewById(R.id.title_back);
		battery = (BatteryCharger) findViewById(R.id.battery_charge);
		userInfoMoreIv = (ImageView) findViewById(R.id.user_info_more);
		awardNumTv = (TextView) findViewById(R.id.user_award_num);
		userNameTv = (TextView) findViewById(R.id.user_name);
		exchangeBtn = (Button) findViewById(R.id.exchange_btn);
		cashOutBtn = (Button) findViewById(R.id.tixian_btn);
		userInfo = (RelativeLayout) findViewById(R.id.user_info);
		weixinAccountEdt = (EditText) findViewById(R.id.weixin_account_edt);
		moneyEdt = (EditText) findViewById(R.id.money_num_edt);
		moneyEdt.setText("5");
		awardNumTv.setText(SharedPreferncesUtil.getMoney(this) + "");

		addBtn = (Button) findViewById(R.id.money_num_add);
		reduceBtn = (Button) findViewById(R.id.money_num_reduce);
		sureBtn = (Button) findViewById(R.id.cash_out_sure);
		cancleBtn = (Button) findViewById(R.id.cash_out_cancle);
		money = Integer.parseInt(moneyEdt.getText().toString());

		if (ChargeApplication.isBoxConnected) {
			battery.setVisibility(View.VISIBLE);
			battery.startChargerAnim();
		}

		addBtn.setOnClickListener(this);
		reduceBtn.setOnClickListener(this);
		sureBtn.setOnClickListener(this);
		cancleBtn.setOnClickListener(this);
		backIv.setOnClickListener(this);
		exchangeBtn.setOnClickListener(this);
		cashOutBtn.setOnClickListener(this);
		userInfoMoreIv.setOnClickListener(this);
		userInfo.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.title_back:
			finish();
			break;
		case R.id.user_name:
			Intent ite = new Intent(this, ModifyNickNameActivity.class);
			ite.putExtra("nickname", userNameTv.getText().toString());
			startActivity(ite);
			break;
		case R.id.user_info_more:
			Intent intent = new Intent(this, CenterActivity.class);
			startActivity(intent);
			break;
		case R.id.exchange_btn:
			Intent it = new Intent(this, ScanActivity.class);
			startActivity(it);
			break;
		case R.id.tixian_btn:

			break;
		case R.id.user_info:
			Intent its = new Intent(this, CenterActivity.class);
			startActivity(its);
			break;
		case R.id.money_num_add:
			money += 1;
			moneyEdt.setText("" + money);
			break;
		case R.id.money_num_reduce:
			if (money > 5) {
				money -= 1;
			}
			moneyEdt.setText("" + money);
			break;
		case R.id.cash_out_sure:
			money = Integer.parseInt(moneyEdt.getText().toString());
			weixinAccount = weixinAccountEdt.getText().toString();
			if (TextUtils.isEmpty(weixinAccount)) {
				ToastUtils.showShort(this, "请填先写微信号");
				return;
			}

			if (money < 5) {
				ToastUtils.showShort(this, "提现金额不能小于5元");
				return;
			}

			awardNum = Float.parseFloat(awardNumTv.getText().toString());
			if (money > awardNum) {
				ToastUtils.showShort(this, "金额超限");
				return;
			}

			String AuthKey = ChargeApplication.getInitInfo().get("AuthKey");
			if (TextUtils.isEmpty(AuthKey) || AuthKey == null) {
				ToastUtils.showShort(this, "用户初始化失败，请稍后重试");
				clientInit();
				return;
			}

			userCashOut(AuthKey);
			break;
		case R.id.cash_out_cancle:
			finish();
			break;
		}
	}

	/**
	 * @描述：
	 * @param AuthKey
	 */
	private void userCashOut(String AuthKey) {
		if (NetUtils.isConnected(this)) {
			request.getRequestData(mHandler, Constant.USER_CASH_OUT, "AuthKey",
					AuthKey, "Money", money + "", "Remark", weixinAccount);
		} else {
			ToastUtils.showShort(this, "提现操作需要连接网络");
		}
	}

}
